package org.jeecg.modules.api.wlhy.evaluation;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.evaluation.entity.HyEvaluation;
import org.jeecg.modules.wlhy.evaluation.service.IHyEvaluationService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Description: 评价接口类
 * @author: luruirui
 * @date: 2020年12月23日 18:26
 */
@Api(tags="APP评价")
@RestController
@RequestMapping("/api/wlhy/evaluation")
@Slf4j
public class ApiEvaluationController extends JeecgController<HyEvaluation, IHyEvaluationService> {
    @Resource
    private BaseCommonService baseCommonService;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private IHyOrderService hyOrderService;
    @Autowired
    private IHyShippingNoteService hyShippingNoteService;
    @Autowired
    private IHyCustomerService hyCustomerService;
    @Autowired
    private IHyDriverService hyDriverService;
    @Autowired
    private  IHyEvaluationService hyEvaluationService;




    /**
     * @description APP评价-评价
     * @param jsonObject
     * @return Result
     */
    @AutoLog(value = "APP评价-评价")
    @ApiOperation(value="APP评价-评价", notes="APP评价-评价")
    @PostMapping(value = "/evaluate")
    public Result<?> evaluate(@RequestBody JSONObject jsonObject) {
        String shippingNoteId = jsonObject.getString("shippingNoteId");
        double score = jsonObject.getDouble("score");
        boolean isCustomer = jsonObject.getBoolean("isCustomer");


        //运单数据
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(shippingNoteId);
        if(hyShippingNote == null){
            return Result.error("根据当前运单id找不到对应运单!");
        }
        HyEvaluation hyEvaluation = hyEvaluationService.getByShippingNoteNumber(hyShippingNote.getShippingNoteNumber());
        boolean isAdd = false;
        //当前时间
        Date date = new Date();
        //SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        if(hyEvaluation == null){
            isAdd = true;
            hyEvaluation = new HyEvaluation();
            hyEvaluation.setCreateTime(date);
        }
        hyEvaluation.setShippingNoteId(shippingNoteId);//设置运单id
        hyEvaluation.setShippingNoteNumber(hyShippingNote.getShippingNoteNumber());//设置运单号
        //货源数据
//        HyOrder order = hyOrderService.getById(hyShippingNote.getOrderId());
//        if(order == null){
//            return Result.error("根据当前运单号找不到所属货源!");
//        }
        hyEvaluation.setAddrSend(hyShippingNote.getSendAddressName());//设置发货地名称
        hyEvaluation.setAddrReceive(hyShippingNote.getReceiveAddressName());//设置收货地名称


        String customerId = hyShippingNote.getCustomerId();//货主id
        String driverId = hyShippingNote.getDriverId();//司机id
        //货主数据
        HyCustomer hyCustomer = hyCustomerService.getById(customerId);
        hyCustomer = hyCustomer == null ? new HyCustomer() : hyCustomer;
        //司机数据
        HyDriver hyDriver = hyDriverService.getById(driverId);
        hyDriver = hyDriver == null ? new HyDriver() : hyDriver;
        //通用设置
        hyEvaluation.setCustomerId(customerId);//设置货主id
        hyEvaluation.setCustomerName(hyCustomer.getCustomerName());//设置货主名称
        hyEvaluation.setCustomerPhone(hyCustomer.getLoginPhone());//设置货主手机
        hyEvaluation.setDriverName(hyDriver.getDriverName());//设置司机名称
        hyEvaluation.setDriverPhone(hyDriver.getTelephone());//设置司机手机
        hyEvaluation.setDriverId(driverId);//设置司机id
        //货主评价
        if(isCustomer){
            hyEvaluation.setCustomerEvaluateTime(date);//设置评价时间
            hyEvaluation.setDriverScore(score);//设置司机得分
        }
        else{
            //司机评价
            hyEvaluation.setDriverEvaluateTime(date);//设置评价时间
            hyEvaluation.setDriverScore(score);//设置司机得分
//            hyEvaluation.setCustomerScore(score);//设置货主得分
        }

        //数据操作
        if(isAdd){
            hyEvaluationService.save(hyEvaluation);
            hyShippingNote.setEvaluationId(hyEvaluation.getId());
            hyShippingNoteService.updateById(hyShippingNote);
        }
        else{
            hyEvaluationService.updateById(hyEvaluation);
        }

        //添加日志
        baseCommonService.addLog(isCustomer ? "货主[" + hyEvaluation.getCustomerName() : "司机[" + hyEvaluation.getDriverName() + "]评价成功！",
                CommonConstant.LOG_TYPE_2, isAdd ? CommonConstant.OPERATE_TYPE_2 : CommonConstant.OPERATE_TYPE_3);
        return Result.OK("评价成功!");
    }

    /**
     * APP评价-分页列表查询
     *
     * @param hyEvaluation
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value="APP评价-分页列表查询", notes="APP评价-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HyEvaluation hyEvaluation,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HyEvaluation> queryWrapper = QueryGenerator.initQueryWrapper(hyEvaluation, req.getParameterMap());
        LoginUser loginUser = UserUtil.getLoginUser();
        String userId = loginUser.getId();
        String userType = loginUser.getUType();
        String id = "";
        String column = "";
        if (userType.equals("2")) {
            QueryWrapper<HyCustomer> wrapper = QueryGenerator.initQueryWrapper(new HyCustomer(), req.getParameterMap());
            wrapper.eq("user_id", userId);
            HyCustomer customer = hyCustomerService.getOne(wrapper);
            id = customer.getId();
            column = "customer_id";
        }
        else
        {
            QueryWrapper<HyDriver> wrapper = QueryGenerator.initQueryWrapper(new HyDriver(), req.getParameterMap());
            wrapper.eq("user_id", userId);
            HyDriver driver = hyDriverService.getOne(wrapper);
            id = driver.getId();
            column = "driver_id";
        }
        queryWrapper.eq(column, id);
        queryWrapper.orderByDesc("create_time");
        Page<HyEvaluation> page = new Page<HyEvaluation>(pageNo, pageSize);
        IPage<HyEvaluation> pageList = hyEvaluationService.page(page, queryWrapper);
        //return Result.OK(pageList);

        //重组结构
        List<HyEvaluation> records = pageList.getRecords();
        List<HashMap> evaluateCustomerList = new ArrayList<>();
        List<HashMap> evaluateDriverList = new ArrayList<>();
        //HyEvaluation dataList[] = {};
        for (HyEvaluation e : records){
            HashMap evaluation = new HashMap<>();
            evaluation.put("shippingNoteNumber", e.getShippingNoteNumber());
            evaluation.put("addrSend", e.getAddrSend());
            evaluation.put("addrReceive", e.getAddrReceive());

            //货主对司机的评价
            if (null != e.getCustomerEvaluateTime()) {
                evaluation.put("id", e.getCustomerId());
                evaluation.put("name", e.getCustomerName());
                evaluation.put("phone", e.getCustomerPhone());
                evaluation.put("evaluateTime", e.getCustomerEvaluateTime());
                evaluation.put("score", e.getDriverScore());//货主评分，司机得分
                evaluateDriverList.add(evaluation);
            }

            //司机对货主的评价
            if (null != e.getDriverEvaluateTime()) {
                //评价货主，对货主评价
                evaluation.put("id", e.getDriverId());
                evaluation.put("name", e.getDriverName());
                evaluation.put("phone", e.getDriverPhone());
                evaluation.put("evaluateTime", e.getDriverEvaluateTime());
                evaluation.put("score", e.getCustomerScore());//司机评分，货主得分
                evaluateCustomerList.add(evaluation);
            }
//            String customerId = e.getCustomerId();
//            if(customerId != null && !customerId.equals("")){
//                //评价货主，对货主评价
//                evaluation.put("id", e.getDriverId());
//                evaluation.put("name", e.getDriverName());
//                evaluation.put("phone", e.getDriverPhone());
//                evaluation.put("evaluateTime", e.getDriverEvaluateTime());
//                evaluation.put("score", e.getCustomerScore());//司机评分，货主得分
//                evaluateCustomerList.add(evaluation);
//            }
//
//            String driverId = e.getDriverId();
//            if(driverId != null && !driverId.equals("")){
//                //评价司机，对司机评价
//                evaluation.put("id", e.getCustomerId());
//                evaluation.put("name", e.getCustomerName());
//                evaluation.put("phone", e.getCustomerPhone());
//                evaluation.put("evaluateTime", e.getCustomerEvaluateTime());
//                evaluation.put("score", e.getDriverScore());//货主评分，司机得分
//                evaluateDriverList.add(evaluation);
//            }
        }
        HashMap evaluationList = new HashMap<>();
        evaluationList.put("evaluateCustomerList", evaluateCustomerList);
        evaluationList.put("evaluateDriverList", evaluateDriverList);
        return Result.OK(evaluationList);
    }

    /**
     * 通过运单号获取评价信息
     * @param shippingNoteNumber 运单号
     * @return
     */
//    @AutoLog(value = "APP评价-通过运单号获取评价信息")
    @ApiOperation(value="APP评价-通过运单号获取评价信息", notes="APP评价-通过运单号获取评价信息")
    @GetMapping(value = "/getByShippingNoteNumber")
    public Result<?> getByShippingNoteNumber(@RequestParam(name="shippingNoteNumber") String shippingNoteNumber) {
        HyEvaluation e = hyEvaluationService.getByShippingNoteNumber(shippingNoteNumber);
        if(e==null) {
            return Result.error("未找到对应数据");
        }
        //重组结构
        HashMap evaluation = new HashMap<>();
        String customerId = e.getCustomerId();
        if(customerId != null && !customerId.equals("")){
            //评价货主，对货主评价
            HashMap evaluateCustomer = new HashMap<>();
            evaluateCustomer.put("id", e.getDriverId());
            evaluateCustomer.put("name", e.getDriverName());
            evaluateCustomer.put("phone", e.getDriverPhone());
            evaluateCustomer.put("evaluateTime", e.getDriverEvaluateTime());
            evaluateCustomer.put("score", e.getCustomerScore());//司机评分，货主得分
            evaluateCustomer.put("shippingNoteNumber", e.getShippingNoteNumber());
            evaluateCustomer.put("addrSend", e.getAddrSend());
            evaluateCustomer.put("addrReceive", e.getAddrReceive());
            evaluation.put("evaluateCustomer", evaluateCustomer);
        }

        String driverId = e.getDriverId();
        if(driverId != null && !driverId.equals("")){
            //评价司机，对司机评价
            HashMap evaluateDriver = new HashMap<>();
            evaluateDriver.put("id", e.getCustomerId());
            evaluateDriver.put("name", e.getCustomerName());
            evaluateDriver.put("phone", e.getCustomerPhone());
            evaluateDriver.put("evaluateTime", e.getCustomerEvaluateTime());
            evaluateDriver.put("score", e.getDriverScore());//货主评分，司机得分
            evaluateDriver.put("shippingNoteNumber", e.getShippingNoteNumber());
            evaluateDriver.put("addrSend", e.getAddrSend());
            evaluateDriver.put("addrReceive", e.getAddrReceive());
            evaluation.put("evaluateDriver", evaluateDriver);
        }

        //添加日志
        baseCommonService.addLog("查询运单[" + shippingNoteNumber + "]的评价信息", CommonConstant.LOG_TYPE_2, CommonConstant.OPERATE_TYPE_1);
        return Result.OK(evaluation);
    }

}
